/**
 *
 */
package com.fita.webpay.helper.impl;

import java.io.IOException;
import java.util.Map;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.demo2do.core.utils.StringUtils;
import com.fita.webpay.helper.SignatureHelper;

/**
 * @author lute
 */
@Component("handpaySignatureHelper")
public class HandpaySigantureHelper implements SignatureHelper {
    
    private final Logger logger = LoggerFactory.getLogger(SignatureHelper.class);

    private String appKey;

    /**
     * Initialize handpay APP key
     * @param appKey 
     */
    @Autowired
    public void initAppKey(@Value("#{payment['handpay.appKey']}") String appKey) throws IOException {
        this.appKey = appKey;
    }

    /* (non-Javadoc)
     * @see com.fita.webpay.helper.SignatureHelper#sign(java.util.Map)
     */
    public String sign(Map<String, String> signatureContext) {
        String queryString = StringUtils.toSortedQueryString(signatureContext);
        return DigestUtils.md5Hex(StringUtils.connect(queryString, "|", appKey));
    }

    /* (non-Javadoc)
     * @see com.fita.webpay.helper.SignatureHelper#check(java.lang.String, java.lang.String)
     */
    public boolean validate(String sortedQueryString, String sign) {
    
        logger.info("get sortedQueryString[{}] and sign[{}]", sortedQueryString, sign);
        
        String queryString = new StringBuilder().append(sortedQueryString)
                .append("|")
                .append(appKey)
                .toString();
        
        logger.info("get queryString[{}]", queryString);

        String signature = DigestUtils.md5Hex(queryString).toUpperCase();
        
        logger.info("get signature[{}]", signature);
        
        return org.apache.commons.lang3.StringUtils.equalsIgnoreCase(signature, sign);
        
    }

    /**
     * @return the appKey
     */
    public String getAppKey() {
        return appKey;
    }

}
